<template>
  <div class="page">
    <div>
      生成方式：
      <el-button
        type="primary"
        size="default"
        @click="exportAll()"
      >
        生成路线图
      </el-button>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import startsPoints from './children/starts'
import endsPoints from './children/ends'

var drivingOption = {
  policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
  ferry: 1, // 是否可以使用轮渡
  province: '京', // 车牌省份的汉字缩写
}

// 构造路线导航类
var driving = new AMap.Driving(drivingOption)

// 解析DrivingRoute对象，构造成AMap.Polyline的path参数需要的格式
// DrivingResult对象结构参考文档 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DriveRoute
function parseRouteToPath (route) {
  var path = []
  for (var i = 0, l = route.steps.length; i < l; i++) {
    var step = route.steps[i]

    for (var j = 0, n = step.path.length; j < n; j++) {
      path.push(step.path[j])
    }
  }
  return path
}

export default {
  data () {
    return {
      data: [
        'SheetJS'.split(''),
        [1, 2, 3, 4, 5, 6, 7],
        [2, 3, 4, 5, 6, 7, 8]
      ]
    }
  },
  mounted () {

  },
  methods: {
    // 导出所有四省地级市
    async exportAll () {
      for (let index = 0; index < startsPoints.length; index++) {
        const start = startsPoints[index]
        await this.exportOne(start)
      }
    },
    // 导出一个四省地级市
    async exportOne (start) {
      const results = []
      const loading = this.$loading({
        lock: true,
        text: '进度 0%',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      for (let index = 0; index < endsPoints.length; index++) {
        const element = endsPoints[index]
        try {
          const path = await this.exportOneLine(start, element)
          results.push(...path)
          const percent = Math.floor(index * 100 / 120)
          loading.text = '进度 ' + percent + '%'
        } catch (err) {
          console.log(err)
        }
      }
      const excelName = start.address
      this.exportFile(excelName, results)
      loading.close()
    },
    exportOneLine (start, end) {
      return new Promise(function (resolve, reject) {
        // 根据起终点经纬度规划驾车导航路线
        driving.search(new AMap.LngLat(start.lng, start.lat), new AMap.LngLat(end.lng, end.lat), function (status, result) {
        // result即是对应的驾车导航信息，相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
          if (status === 'complete') {
            if (result.routes && result.routes.length) {
            // 绘制第一条路线，也可以按需求绘制其它几条路线
              const path = parseRouteToPath(result.routes[0])
              resolve(path.map((ele, index) => {
                return [
                  ele.lng,
                  ele.lat,
                ]
              }))
            }
          } else {
            // console.log('获取驾车数据失败：' + result)
            reject(new Error('获取驾车数据失败：' + result))
          }
        })
      })
    },

    exportFile (excelName, data) {
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['经度', '纬度']
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: excelName,
          autoWidth: true,
          bookType: 'csv'
        })
      })
    },
    exportFile2 (excelName, data) {
      /* Initial row */
      var ws = XLSX.utils.aoa_to_sheet([
        ['序号', '经度', '纬度'],
        ...data
      ])
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'SheetJS')
      /* generate file and send to client */
      XLSX.writeFile(wb, excelName + '.xlsx')
    },
  }
}
</script>

<style lang="scss" scoped>
.page{
  padding: 30px;
}
</style>
